// pages/search/search.js
const app = getApp();
const request = require('../../utils/request.js');
const config = require('../../utils/config');
const util = require('../../utils/util');
const cache = require('../../utils/cache');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    colorTheme: app.globalData.colorTheme,
    query: "",
    pageNum: 1,
    pageSize: 10,
    params: {},
    searchResult: [],
    historyList: []
  },

  /**
   * 监听搜索文本框内容变化
   */
  changeQuery(e){
    this.setData({
      query: e.detail.value,
      params: {}
    });
  },

  /**
   * 清空搜索文本框
   */
  clearQuery(){
    this.setData({
      query: "",
      searchResult: []
    });
  },

  /**
   * 提交搜索内容
   */
  submitSearch(e){
    let query = e.detail.value;
    this.setData({
      query,
      pageNum: 1,
      params: { title: query },
      searchResult: [],
      historyList: cache.saveSearch(query)
    });
    this.getSearchResult(this.data.pageNum, this.data.pageSize, this.data.params);
  },

  /**
   * 获取搜索结果
   */
  getSearchResult(pageNum, pageSize, params){
    let token = wx.getStorageSync('token');
    let url = config.SERVER_URL + 'index/list/post/?pageNum=' + pageNum + '&pageSize=' + pageSize;
    let that = this;
    wx.showLoading({
      title: '加载ing',
    })
    request.requestGetApi(url, token, params, 'application/json').then(res=>{
      if(res.status === config.STATUS_OK){
        let isResult = res.data.rows.length >= pageSize;
        res.data.rows.forEach(item => {
          item.content = util.filterContent(item.content);
        });
        this.setData({
          isResult,
          searchResult: that.data.searchResult.concat(res.data.rows)
        });
      }
    }).catch(err=>{
      app.failFun(err);
    }).finally((res) => {
      app.completeFun(res);
    });
  },

  /**
   * 跳转到帖子详情页
   */
  toPostInfo(e){
    if(!app.checkedUserLoading()){
      return;
    }
    wx.navigateTo({
      url: '/pages/post/post?postId=' + e.currentTarget.dataset.postid
    });
  },

  /**
   * 清空搜索历史纪录
   */  
  clearSearchHistory(){
    wx.showModal({
      title: '提示',
      content: '是否清空搜索记录？',
      confirmText: '确定',
      confirmColor: '#e54d42',
      success: (result) => {
        if(result.confirm){
          this.setData({
            historyList: cache.clearSearch()
          })
        }
      }
    });
  },

  /**
   * 删除单个历史搜索记录
   */  
  deleteSearchHistory(e){
    let query = e.currentTarget.dataset.query;
    wx.showModal({
      title: '提示',
      content: '是否删除"' + query + '"记录？',
      confirmText: '确定',
      confirmColor: '#e54d42',
      success: (result) => {
        if(result.confirm){
          this.setData({
            historyList: cache.deleteSearch(query)
          })
        }
      }
    });
  },

  /**
   * 选择历史搜索记录
   */
  selectHistory(e){
    let tmp = {
      detail: {
        value: e.currentTarget.dataset.query
      }
    }
    this.submitSearch(tmp);
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      historyList: cache.loadSearch()
    });
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if(!this.data.isResult){
      return;
    }
    let pageNum = this.data.pageNum + 1;
    this.setData({
      pageNum: pageNum
    });
    this.getSearchResult(pageNum, this.data.pageSize, this.data.params);
  },
})